export function clone(d: Date) {
  return new Date(d.getTime());
}

export function addDays(d: Date, days: number) {
  const newDate = clone(d);
  newDate.setDate(d.getDate() + days);
  return newDate;
}

export function addMonths(d: Date, months: number) {
  const newDate = clone(d);
  newDate.setMonth(d.getMonth() + months);
  return newDate;
}

export function getFirstDayOfMonth(d: Date) {
  return new Date(d.getFullYear(), d.getMonth(), 1);
}

export function getFirstDayOfSeason(d: Date) {
  let m = d.getMonth();
  m = m - (m % 3);
  return new Date(d.getFullYear(), m, 1);
}

export function getFirstDayOfYear(d: Date) {
  return new Date(d.getFullYear(), 0, 1);
}

export function getDaysInMonth(d: Date) {
  const resultDate = getFirstDayOfMonth(d);

  resultDate.setMonth(resultDate.getMonth() + 1);
  resultDate.setDate(resultDate.getDate() - 1);

  return resultDate.getDate();
}
export function format(date: any, fmt?: string) {
  if (!date) {
    return '';
  }
  if (typeof date === 'string') {
    if (date.substring(0, 10) === '0001-01-01') {
      return '';
    }
  }
  let _date = date;
  if (!(date instanceof Date)) {
    _date = convert(date);
  }
  if (isNaN(_date.getTime())) {
    return '';
  }
  if (_date.getFullYear() <= 1970) {
    return '';
  }
  const year = `${_date.getFullYear()}`;
  let month = `${_date.getMonth() + 1}`;
  if (month.length === 1) {
    month = `0${month}`;
  }
  let day = `${_date.getDate()}`;
  if (day.length === 1) {
    day = `0${day}`;
  }

  let hours = `${_date.getHours()}`;
  if (hours.length === 1) {
    hours = `0${hours}`;
  }
  let minutes = `${_date.getMinutes()}`;
  if (minutes.length === 1) {
    minutes = `0${minutes}`;
  }
  let seconds = `${_date.getSeconds()}`;
  if (seconds.length === 1) {
    seconds = `0${seconds}`;
  }
  return (fmt || 'yyyy-MM-dd')
    .replace(/yyyy/g, year)
    .replace(/MM/g, month)
    .replace(/dd/g, day)

    .replace(/hh/g, hours)
    .replace(/mm/g, minutes)
    .replace(/ss/g, seconds);
}
// string, unixtimestamp convert to Date
export function convert(obj: any, def?: any) {
  let _def = def;
  if (_def === undefined) {
    _def = new Date();
  }
  if (!obj) {
    return def;
  }
  let _obj = obj;
  if (obj instanceof Date) {
    return obj;
  }
  if (/^[-+]?[0-9]+$/.test(obj)) {
    _obj = parseInt(obj);
  }
  _obj = new Date(obj);
  // Invalid Date
  if (isNaN(_obj.getTime())) {
    _obj = _def;
  }
  return _obj;
}
